package com.lagou.edu.filter;

import com.lagou.edu.bean.LimitTimes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @Author 梅松
 * @Date 2021/10/23 16:50
 */
@Slf4j
@Component
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class RegisterLimitFilter implements GlobalFilter, Ordered {
    //IP注册次数，使用Map缓存
    private Map<String,LimitTimes> registLimitMap = new ConcurrentHashMap<>();

    @Value("${register.limitTimes}")
    private int limitTimes;
    @Value("${register.duration}")
    private int duration;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();

        // 访问路径
        String path = request.getURI().getPath();

        if (path.startsWith("/api/user/register"))
        {
            synchronized (RegisterLimitFilter.class){
                LimitTimes times = registLimitMap.get(clientIp);
                //如果为空，或过期，重新设置
                if(times == null || isDurationEnd(times)){
                    times = new LimitTimes();
                    times.setTimes(0);
                    times.setBeginTime(new Date());
                }
                if(times == null){
                    log.info(clientIp+"创建limitTimes");
                }
                if(isDurationEnd(times)){
                    log.info(clientIp+"重置limitTimes");
                }

                if (limitTimes == times.getTimes())
                {
                    response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                    String data = "您频繁进⾏注册，请求已被拒绝";
                    DataBuffer wrap =
                            response.bufferFactory().wrap(data.getBytes());

                    response.getHeaders().add("Access-Control-Allow-Origin", "*");
                    return response.writeWith(Mono.just(wrap));
                }

                //增加时间
                times.setTimes(times.getTimes()+1);
                registLimitMap.put(clientIp,times);
                log.info(clientIp+":"+times.toString());
            }

        }

        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 判断是否超过间隔时间
     * @param limitTimes
     * @return
     */
    private boolean isDurationEnd(LimitTimes limitTimes){
        //获取开始时间
        Date beginTime = limitTimes.getBeginTime();
        //计算结束时间
        Calendar c = Calendar.getInstance();
        c.setTime(beginTime);
        c.add(Calendar.SECOND,duration);
        Date endTime = c.getTime();
        //判断是否超过
        return new Date().after(endTime);
    }
}
